/**
 * 用于绑定entity的扩展属性值
 */
function bindEntityDatum($dom) {
	var basFS = $("fieldset", $dom);
	var entityId = $dom.attr("entity_id"), categoryId = $dom.attr("category_id");
	var url = entityId ? "datum/" + entityId : "category/" + categoryId + "/datum";
	DWZ.get(url, function(data) {
		var types = data && data.result ? data.result : {};
		var fsParent = basFS.parent();
		$.each(types, function(i, type) {
			if (type && type.attribute) {
				var nFS = $("<fieldset><legend>" + type.name + "</legend></fieldset>");
				fsParent.append(nFS);
				// debugger;
				$.each(type.attribute, function(i, attr) {
					// if(i<2)
					// debugger;
					var p = $("<p></p>");
					p.append("<label>" + attr.title + "：</label>");
					var val;
					if (attr.datatype == "select") {
						val = "<select name='" + attr.value_id + " id=value_id_" + attr.attribute_id + "' datas='" + attr.opvalue + "' defSelValue='" + attr.value + "'></select>";

					} else if (attr.datatype == "date") {
						if (attr.rule)
							attr.rule = eval("(" + attr.rule + ")");
						val = $("<input class='" + (attr.rule || "") + "' readonly='true' id=value_id_" + attr.attribute_id + " name='value_id_" + attr.attribute_id
								+ "' valueId='" + (attr.value_id || "") + "' type=text size=30 value='" + (attr.value || "") + "' />");
						$.each(attr.rule, function(k, v) {
							val.attr("" + k, v);
						})
					} else {
						val = "<input class='" + attr.datatype + "' id=value_id_" + attr.attribute_id + " name=value_id_" + attr.attribute_id + " valueId='"
								+ (attr.value_id || "") + "' type=text size=30 value='" + (attr.value || "") + "' rule='" + (attr.rule || "") + "' />";
					}
					p.append(val);
					nFS.append(p);
				})
				initUI(nFS);
				$("select", nFS).jBindCombox();
			}
		})
		$("fieldset>legend", fsParent).attr("title", "收缩").each(function() {
			var $this = $(this);
			$this.click(function() {
				$this.toggleClass("collapsable");
				if ($this.hasClass("collapsable")) {
					$this.attr("title", "展开").siblings().hide();
				} else {
					$this.attr("title", "收缩").siblings().show();
				}
			});
		});
	});
}
/**
 * 绑定动态列
 * 
 * @param $panel
 */
function panelLoaded($page) {
	var categoryId = $page.attr("categoryId"), sign = $page.attr("sign");
	var url = "category/" + categoryId + "/extdefined?sign=" + sign;
	DWZ.get(url, function(data) {
		if (typeof (data) == "string")
			data = eval("(" + data + ")");

		data = data.result || {};
		var table = $("table.list", $page);
		table.find(">thead>tr>th[ext=true],>tbody>tr>td[ext=true]").remove();
		// table.find(">tbody>tr>td[ext=true]").remove();
		// $("tbody.list",table).data("param",{fields:data.show_fields});
		var extTh = table.find(">thead>tr>th[extcol=true]");
		var extTd = table.find(">tbody.templet>tr>td[extcol=true]");
		var content = eval("(" + data.content + ")");
		$.each(data.show_fields.split(","), function(i, v) {
			var attr = content.attribute[v];
			var th = "<th name='"+v+"' ext='true' "+(attr.width?"width='"+attr.width+"'":"")+">" + attr.name + "</th>";
			extTh.before(th);
			var td = "<td ext='true' class='" + (attr.change === false ? "edit" : "") + "' field='" + v + "' name='" + v + "' format='" + (attr.format || "") + "' align='"+(attr.align||"")+"'>${" + v
					+ "}</td>";
			extTd.before(td);
		});
		var $list = table.find(">tbody.list");
		$list.attr("action", $list.attr("url"));
		
		var isShowAllSearcherItem=function($cont,isShow){
			//if ( !($.browser.msie && $.browser.version=="6.0") )return;
			var cWidth=$cont.width(),pWidth=$cont.find(".fields").children().eq(0).width();
			var num=parseInt(cWidth/pWidth);
			if(isShow){
				$cont.find(".fields").children().eq(num-1).nextAll().show();
			}else{
				$cont.find(".fields").children().eq(num-1).nextAll().hide();
			}
		}
		
		var $searchMore = $page.find(".searchBar .more").attr("url", content.searcher)//.click(function() {
		searchBlock($searchMore);
		
		var $searchBar=$page.find(".searchBar");
		
		isShowAllSearcherItem($searchBar.find(".searchContent"),false);
		$searchMore.toggle(function() {
			$searchBar.css("z-index", 0).removeClass("searchShow").find(".more").removeClass("moreExpandable").addClass("moreCollapsable");
			isShowAllSearcherItem($searchBar.find(".searchContent"),false);
		}, function() {
			$searchBar.css("z-index", 3).addClass("searchShow").find(".more").removeClass("moreCollapsable").addClass("moreExpandable");
			isShowAllSearcherItem($searchBar.find(".searchContent"),true);
		});
		if (!table.attr("loaded"))
			setTimeout(function(){$searchMore.click();},100);
			
		// initUI($panel);
		table.removeAttr('loaded').jBinds();
		// debugger;
	}, false);
	
	bindEntityColumnSum($page.find('.sumtotal[action]'));
}

// 搜索页面
function searchBlock(dom) {
	var $dom = $(dom);
	if ($dom.data("loaded"))
		return;
	var url = $dom.attr("url"), $content = $dom.parents(".searchBar").eq(0).find(".searchContent");

	// 搜索页面不能新增、删除，所以屏蔽新增、删除按钮
	var page = $dom.parents(".page");
	if (page.attr("categoryId") == 0) {
		var toolBar = page.find("ul[class=toolBar]");
		toolBar.find("a[class=add]").hide();
		toolBar.find("a[class=delete]").hide();
	}
	$content.load(url, function() {
		initUI($content);
		var h = $content.find(".searchBar .searchContent .fields").height();
		var height = 0;
		if (h != null)
			height = h;
		else if ($content.find(".searchBar .searchContent .fields").length > 0) {
			height = $content.find(".searchBar .searchContent .fields")[0].scrollHeight;
		}
		if (height < 25 * 2)
			$content.find(".searchBar .more").hide();
	});
	$dom.data("loaded", true);
}
/**
 * 绑定选用的列，主要在cols.html中用到
 * 
 * @param categoryId
 * @param $dom
 */
function bindUsedFields(categoryId, $dom) {
	var url = "category/" + categoryId + "/extdefined?sign=" + $dom.attr("sign");
	DWZ.get(url, function(data) {
		if (typeof (data) == "string")
			data = eval("(" + data + ")");

		data = data.result || {};
		data.show_fields = data.show_fields.split(",");
		data.used_fields = data.used_fields.split(",");
		data.isShowField = function(fieldName) {
			for ( var i in data.show_fields) {
				if (data.show_fields[i] == fieldName)
					return true;
			}
			return false;
		}
		$.each(data.used_fields, function(i, v) {
			var content = eval("(" + data.content + ")");
			$dom.append("<label><input type='checkbox' name='" + v + "' value='" + v + "' " + (data.isShowField(v) ? "checked='checked'" : "") + "/>" + content.attribute[v].name
					+ "</label>");
		});
	}, "json")
}
/**
 * 绑定扩展字段
 * 
 * @param $dom
 * @param values
 * @method "UPDATE","ADD","add","update"
 */
function bindExtField($dom, values, method) {
	if (values == "UPDATE" || values == "update" || values == "ADD" || values == "add") {
		method = values;
		values = {};
	} else {
		values = values || {};
	}

	var categoryId = $dom.attr("category_id");
	var url = "category/" + categoryId + "/extdefined?sign=" + $dom.attr("sign");
	DWZ.get(url, function(data) {
		if (typeof (data) == "string")
			data = eval("(" + data + ")");
		data = data.result || {};
		data.show_fields = data.show_fields.split(",");
		data.used_fields = data.used_fields.split(",");
		// data.op_values=data.op_values.split(",");

		var basFS = $("fieldset", $dom);
		var fsParent = basFS.parent();
		var nFS = $("<fieldset><legend>" + data.title + "</legend></fieldset>");
		fsParent.append(nFS);
		var content = eval("(" + data.content + ")");
		$.each(content.attribute, function(k, v) {
			if ((method.toLowerCase() == "add") && v.add === false)
				return;
			if ((method.toLowerCase() == "update") && v.update === false)
				return;
			var val = "";
			var p;
			var readonly = v.add === false ? "readonly" : ""; // 新增时没有的字段，修改时也不允修改（因为是系统自动统计的信息）
			var opValues = eval("(" + data.op_values + ")");
			if (v.rule.indexOf("hide") < 0) {
				p = $("<p></p>");
				p.append("<label>" + v.name + "：</label>");
			} else {
				p = $("<span class='hide'></span>");
			}
			if (v.rule.indexOf("tree") >= 0 && opValues) { // 绑定树形数据
				val = "<input class='tree textInput readonly valid' readonly='true' name='" + k + "' type='text' size='30' value='" + (values[k] || "")
						+ "' onclick='$(this).next(\"a\").click()' " + readonly + " />";
				var params = typeof (opValues[k]) != "string" ? "category_id=" + opValues[k] : "category_id=0&entity=" + opValues[k];
				val += "<a url='entity/tree.html?" + params + "&type=treeRadio' callback='selectTree' target='dialog' width='300' height='450' style='display: none'>选择" + v.name
						+ "</a>";
			} else if (opValues[k]) { // 绑定下拉框，复选框数据
				var vals = opValues[k].split(",");
				var chks = opValues[k].split(";");
				if (vals.length > 1) {
					val = "<select name='" + k + "' datas='" + opValues[k] + "' defSelValue='" + values[k] + "' " + readonly + " ></select>";
				} else if (chks.length > 1) {
					var vals = values[k] ? values[k].split(",") : [];
					for ( var i = 0; i < chks.length; i++) {
						var checked = vals.length > 0 && vals.indexOf(chks[i]) >= 0 ? "checked=checked" : "";
						val += "<label style='float:none;padding:0 5px 0 0;line-height:10px;'><input type='checkbox' name='" + k + "' value='" + chks[i] + "' " + checked + " />"
								+ chks[i] + "</label>";
					}
					val = "<span style='float:right;width:230px;'>" + val + "</span>";
				} else if (v.rule && v.rule.indexOf("date") >= 0) {
					val = "<input class='" + (v.rule || "") + "' readonly='true' name='" + k + "' type='text' size='30' value='" + (values[k] || opValues[k]) + "' />";
				} else {
					val = "<input class='" + v.rule + "' id='" + k + parseInt(Math.random() * 10000) + "' name=" + k + " type=text size=30 value='" + (values[k] || opValues[k])
							+ "' " + readonly + " />";
				}
			} else { // 绑定input框数据
				if (v.rule && v.rule.indexOf("date") >= 0) {
					if (typeof (values[k]) == "undefined") {
						values[k] = "";
					}
					if(readonly=="readonly")
						v.rule = v.rule.replace("date","");
					val = "<input class='" + (v.rule || "") + "' readonly='true' name='" + k + "' type='text' size='30' value='"+(values[k].substr(0,10)||"")+"' />";
				}else{
					val="<input class='"+v.rule+"' id='"+k+parseInt(Math.random()*10000)+"' name="+k+" type=text size=30 format='"+(v.format||"")+"' value='"+(values[k]||"")+"' maxlength='"+v.length+"' "+readonly+" />";
				}
			}
			p.append(val);
			var $input = p.find("input");
			for ( var i = 0; i < bindExtField.prototype.validField.length; i++) {
				if (v[bindExtField.prototype.validField[i]])
					$input.attr("" + bindExtField.prototype.validField[i], v[bindExtField.prototype.validField[i]]);
			}
			nFS.append(p);
		});
		initUI(nFS);
		$("select", nFS).jBindCombox();
		bindEntityDatum($dom);
	}, "json")
}

bindExtField.prototype = {
	validField : [ "maxlength", "minlength", "max", "min", "format", "length" ]
}

/**
 * 将entity导出
 * 
 * @param dom
 */
function exportEntity(dom) {
	var $dom = $(dom);
	if ($dom.parents(".pageContent").eq(0).find(".tableList>table.list>tbody.list").find(".nodate").length > 0) {
		alertMsg.error("没有可导出的数据！");
		return false;
	}

	var url = $dom.attr("url");
	var param = $dom.parents(".pageContent").eq(0).find(".tableList>table.list>tbody.list").data("param") || {};
	var param1 = $("table.list tbody.list").data("param");

	// 因为url中带有中文，所以需要转码，而且需要进行两次转码（进行一次转码，在后台解码会有错误）
	url = url + (url.indexOf('?') == -1 ? "?" : "&") + "condition=" + (param.condition || "") + "&sumEntityExtFields=payprice";
	url = encodeURI(url);

	var iframe = $("<iframe height=0px width=0px style='height:0px;display:none;'></iframe");
	iframe.load(function() {
	});
	iframe.attr("src", url);
	iframe.appendTo($dom.parent());
}
/**
 * 选择树，主要是针对input
 * 
 * @param dom
 */
function selectTree(data, $dom) {
	$dom.siblings("input").val(data.name || data.description);
	// var a=data;
}
/**
 * 绑定总统计
 * @param $dom
 */
function bindEntityColumnSum($dom,$from){
	if($dom.length==0) return;
	var url=$dom.attr("action");
	var param =$from? $from.data("param"):"";
	
	//车管所定制
	//if(param=="" || param.condition.indexOf('str22%20like')<0){
		//$dom.hide();
		//return;
//	}

	DWZ.get(url,param,function(json){
		$dom.show();
		var data=json.result||{};
		$.each(data,function(k,v){
			if(v!=null && v!="")
				$dom.find("[value="+k+"]").text(v.format("#,###.##"));
			else
				$dom.find("[value="+k+"]").text(0.00);
		})
	})
}